/*
 * UCardImageServlet.java
 *
 * Created on June 5, 2007, 6:00 PM
 */
package wap.rockvilletech.util.imaging;

import java.awt.image.BufferedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.imageio.ImageIO;
import java.net.URL;
import java.util.*;
import org.apache.log4j.Logger;

import wap.rockvilletech.portal.SystemProperty;
import wap.rockvilletech.portal.UGreetingsBean;

/**
 *
 * @author tazzix
 * @version
 */
@SuppressWarnings("serial")
public class UCardImageServlet extends HttpServlet {

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    private static final Logger log = Logger.getLogger(UCardImageServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //--System.out.println("Imagesrv Servlet class is called...!");
        //--public boolean debug = false;
        ProcessUCard puc;
        String cid = request.getParameter("cid") != null ? request.getParameter("cid").toString().trim() : "";
        //--request.getParameter("ua") != null ? request.getParameter("ua").toString().trim() : "";
        int h = request.getParameter("h") != null ? Integer.parseInt(request.getParameter("h")) : 300;
        int w = request.getParameter("w") != null ? Integer.parseInt(request.getParameter("w")) : 250;
        HashMap hm_Content = new HashMap();
        ArrayList arr_cnt = new ArrayList();

        String path = null;
        String path_RockvilleImage = null;
        boolean anim = false; //check weather the image is to be animated or not
        String strAnim = "";
        String img = "";
        String strS = "";
        String useRepository = "";
        String strSenderName = "";
        String strSenderMessage = "";
        boolean isValid = true;
        boolean isEditingImage = false;

        try {
            //anim = request.getParameter("anim") != null ? (request.getParameter("anim").toString().equals("1")?true:false) : false;
        	strSenderName = request.getParameter("sendername");
            strSenderMessage = request.getParameter("sendermessage");
//            log.debug("strSenderName: " + strSenderName+", strSenderMessage: " + strSenderMessage);


            strSenderName = ((strSenderName == null) || (strSenderName.equalsIgnoreCase(""))) ? "" : strSenderName;
            strSenderMessage = ((strSenderMessage == null) || (strSenderMessage.equalsIgnoreCase(""))) ? "" : strSenderMessage;
            try {
                strSenderName = java.net.URLDecoder.decode(strSenderName, "UTF-8");
            } catch (Exception exGetSenderName) {
                //strSenderName="";
                log.error("Exception occured while decoding string strSenderName: ", exGetSenderName);
            }
            try {
                strSenderMessage = java.net.URLDecoder.decode(strSenderMessage, "UTF-8");
            } catch (Exception exGetSenderName) {
                //strSenderMessage="";
                log.error("Exception occured while decoding string strsendermessage: ",exGetSenderName);
            }

            try {
                strAnim = (String) request.getParameter("anim");
            } catch (Exception exGetParameter) {
                exGetParameter.printStackTrace();
                log.error("strAnimation Exception :",exGetParameter);
            }
            try {
                anim = ((strAnim == null) || (!strAnim.equalsIgnoreCase("1"))) ? false : true;
            } catch (Exception exComp) {
                log.error("Comp Exception :" ,exComp);
            }
            try {
                img = (String) request.getParameter("img");
            } catch (Exception exGetParameter) {
                log.error("strAnimation Exception :" + exGetParameter);
            }
            try {
                strS = (String) request.getParameter("s");
            } catch (Exception exGetParameter) {
            }
            try {
                useRepository = (String) request.getParameter("repo");
            } catch (Exception exGetParameter) {
            }

            if (strSenderName.trim().equalsIgnoreCase("") || strSenderMessage.trim().equalsIgnoreCase("")) {
                isEditingImage = false;
            } else {
                isEditingImage = true;
            }

            // programmer can set the repositor path, from where to get the images
            if (useRepository != null && useRepository.equalsIgnoreCase("internal")) {
                // use the websites internal image directory
                path = new java.io.File(getServletContext().getRealPath("")).toString() + "/images/";
            } else if (useRepository != null && useRepository.equalsIgnoreCase("HTTP")) {
                // images will directly be downloaded from web
                path = "";
            } else if (useRepository.equalsIgnoreCase("CBP")) {
                // use the Original Content repository
                path = SystemProperty.getProperty("ugreetings_content_basepath");
            } else {
                // use the Sample Content repository
            	path = SystemProperty.getProperty("ugreetings_sample_basepath");
            }
            
            log.debug("Image: " + path + img);
            

            //path=new java.io.File(getServletContext().getRealPath("")).toString();
            if (!path.endsWith("\\") && !path.endsWith("/") && !(useRepository.equalsIgnoreCase("HTTP"))) {
                path += "/";
            }
            if (img.indexOf(".gif") > 0) {
                response.setContentType("image/gif");
                try {
                    AnimatedGifEncoder.genImage(path + img, response.getOutputStream(), strS, w, anim);
                } catch (Exception ex) {
                    log.error("Error Image: " + path + img,ex);
                }

                return;
            }

            response.setContentType("image/jpeg");
            ServletOutputStream sos = response.getOutputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            String imgPath = path + img;
            BufferedImage image = null;

            if (imgPath.trim().toLowerCase().indexOf("http://") < 0) {
                try {
                    image = ImageIO.read(new File(imgPath));
                } catch (Exception notFoundEx) {
                    isValid = false;
                    log.error("FATAL: Unable to find Image: " + imgPath, notFoundEx);
                }
            } else {

                imgPath = java.net.URLDecoder.decode(imgPath, "UTF-8");
                image = loadImage(imgPath);
            }

            if (!isValid) {
                return;
            }

            if (isEditingImage) {
                puc = new ProcessUCard();
                // get data from Content table
                UGreetingsBean db_Card_Cnt = new UGreetingsBean();
                arr_cnt = db_Card_Cnt.getCardDetail(cid);

                hm_Content.put("cid", arr_cnt.get(0));
                hm_Content.put("Point1", arr_cnt.get(1).toString());
                hm_Content.put("Point2", arr_cnt.get(2).toString());
                hm_Content.put("Bias", arr_cnt.get(3).toString());
                hm_Content.put("FillColor", arr_cnt.get(4).toString());
                hm_Content.put("h", h);
                hm_Content.put("w", w);
                hm_Content.put("imgPath", imgPath);
                hm_Content.put("sndrName", strSenderName);
                hm_Content.put("recvName", strSenderMessage);
                hm_Content.put("water_mark", "PREVIEW");

                //--image = puc.processCard(imgPath, strSenderMessage, strSenderName, w,h);
                image = puc.processCard(hm_Content);
            } else {

                //BufferedImage image = ImageIO.read( new File(img ) );

                if (image == null) {
                    //System.out.println("IMAGE NULL!");
                    return;
                }

                if (w >= image.getWidth()) {
                    w = image.getWidth();
                }

                if (strS == null || strS.equalsIgnoreCase("1")) {
                    //System.out.println("");
                } else {
                    //int h = Integer.parseInt( requesst.getParameter("h") );

                    if (request.getParameter("crop") == null) {
                    	log.debug("SCALE:" + w + ":" + w + ":" + image.getHeight() + ":" + image.getWidth());
                        ParameterBlock pb = new ParameterBlock();
                        pb.addSource(image);
                        pb.add(((float) w / image.getWidth()));
                        pb.add(((float) w / image.getWidth()));                        
                        //pb.add( ((float)h/image.getHeight()) );
                        pb.add(0.0F);
                        pb.add(0.0F);                        
                        pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
                        image = JAI.create("scale", pb).getAsBufferedImage();                        
                    } 
                    else {
                        float fWedge = ((float) image.getWidth() / 2.0f) - ((float) w / 2.0f);
                        float fHedge = ((float) image.getHeight() / 2.0f) - ((float) h / 2.0f);
                        log.debug("CROP:" + fHedge + ":" + fWedge + ":" + image.getHeight() + ":" + image.getWidth());
                        ParameterBlock pb = new ParameterBlock();
                        pb.addSource(image);
                        pb.add(fWedge);
                        pb.add(fHedge);
                        pb.add((float) image.getWidth() - (fWedge * 2));
                        pb.add((float) image.getHeight() - (fHedge * 2));
                        image = JAI.create("crop", pb).getAsBufferedImage();
                    }
                }

            } //isEditing check ENDS

            ImageIO.write(image, "jpeg", baos);
            byte[] bytes = baos.toByteArray();

            try {
                sos.write(bytes);
            } catch (Exception e) {
                log.error("Image Path: " + path + img, e);
            }
            sos.close();

        } catch (Exception e) {
            log.error("Error Image: " + path + img, e);
        }
    }

    /**
     * Added to fetch images from the web on runtime.
     * @param name
     * @return
     */
    public BufferedImage loadImage(String name) {
//        log.debug("name: " + name);
        URL url = null;
        try {
            if (name.indexOf("://") < 0) {
                //System.out.println("in :// index less than zero in "+org.openinstaller.util.ClassUtils.getFQMethodName());
                url = new URL("file:///" + name); //getClass().getClassLoader().getResource(name);
            } else {
                //System.out.println("in :// index less than zero in "+org.openinstaller.util.ClassUtils.getFQMethodName());
                url = new URL(name);
            }
            //System.out.println("com.rockville.telenor.Config.getStrUrl_ReurtersWebPage(): "+com.rockville.telenor.Config.getStrUrl_ReurtersWebPage()+" in method:"+org.openinstaller.util.ClassUtils.getFQMethodName());
//            log.debug("is not reuters: " + name);
            return ImageIO.read(url);

        } catch (Exception ex) {
            log.error("loadImage",ex);
            return null;
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
